# -*- coding: utf-8 -*-

'''
打包复制文件的脚本---
'''
import os
import shutil


import re
import os
import tempfile


class Properties:

    def __init__(self, file_name):
        self.file_name = file_name
        self.properties = {}
        try:
            fopen = open(self.file_name, 'r')
            for line in fopen:
                line = line.strip()
                if line.find('=') > 0 and not line.startswith('#'):
                    strs = line.split('=')
                    self.properties[strs[0].strip()] = strs[1].strip()
        except Exception:
            #raise Exception
            print("read file exception ...");
        else:
            fopen.close();

    def has_key(self, key):
        return key in self.properties

    def get(self, key, default_value=''):
        if key in self.properties:
            return self.properties[key]
        return default_value

    def put(self, key, value):
        self.properties[key] = value
        replace_property(self.file_name, key + '=.*', key + '=' + value, True)


def parse(file_name):
    return Properties(file_name)


def replace_property(file_name, from_regex, to_str, append_on_not_exists=True):
    tmpfile = tempfile.TemporaryFile()

    if os.path.exists(file_name):
        r_open = open(file_name, 'r')
        pattern = re.compile(r'' + from_regex)
        found = None
        for line in r_open:
            if pattern.search(line) and not line.strip().startswith('#'):
                found = True
                line = re.sub(from_regex, to_str, line)
            tmpfile.write(bytes(line, encoding="utf8"))
        if not found and append_on_not_exists:
            tmpfile.write( bytes('\n' + to_str ,encoding="utf-8"))
        r_open.close()
        tmpfile.seek(0)

        content = tmpfile.read()

        if os.path.exists(file_name):
            os.remove(file_name)

        w_open = open(file_name, 'w')
        w_open.write(str(content,encoding="utf-8"))
        w_open.close()

        tmpfile.close()
    else:
        print("file %s not found" % file_name);



def del_folder(path):
    for i in os.listdir(path):
        path_file = os.path.join(path, i)  # 取文件绝对路径
        if os.path.exists(path_file):
            if os.path.isfile(path_file):
                os.remove(path_file);
                print("remove " + path_file);
            else:
                shutil.rmtree(path_file)  # 递归删除文件夹
                print("rmtree " + path_file);


'''
初始化创建需要的文件夹
'''
def init_mkdir_folder(path,list_folder):
    for i in list_folder:
        path_file = os.path.join(path, i)  # 取文件绝对路径
        if False == os.path.exists(path_file):
            os.mkdir(path_file);

if __name__ == '__main__':
    print("start");

    property = Properties("./sys.properties");  # 读取文件
    #复制到这个路径
    basePath = property.get("basePath");

    #project_list = ["game-baccara","game-bullfight","game-channel","game-consumer","game-dragon-tiger","game-fores","game-fruit-machine","game-gold-flower","game-landlords","game-provider","game-red-black","game-texas-poker","game-turn-taurus"];
    project_list = property.get("project_list").strip().split(",");

    init_mkdir_folder(basePath,project_list);


    #target包的路径
    targetPackagePath = property.get("targetPackagePath");
    del_folder(basePath);


    print(" start mkdir folder ...")
    folerCount = 0;
    for package in project_list:
        if False == os.path.exists(basePath + package):
            os.mkdir(basePath + package);
            folerCount = folerCount + 1;
            print("mkdir " + basePath + package)

    print(" end mkdir folder ...")
    print("mkdirs folder count :" + str(folerCount));

    print("start copy  package ...")



    target = "/target/";
    lib = "lib/";

    #jar后缀
    jarSuffix = "-1.0-SNAPSHOT.jar";
    game_provider_api = "game-provider-api-1.0-SNAPSHOT.jar";
    game_engine = "game-engine-1.0-SNAPSHOT.jar";

    #war的后缀
    warSuffix = "-1.0-SNAPSHOT";
    ROOT = "/ROOT";
    for package in project_list:
        if os.path.exists(targetPackagePath + package + target  + package + jarSuffix):
            shutil.copy(targetPackagePath + package + target  + package + jarSuffix, basePath+package );
            shutil.copy(targetPackagePath + package + target + lib +  game_provider_api, basePath + package + "/" + game_provider_api);
            print("copy " + targetPackagePath + package + target + package + jarSuffix);
            print("copy api " + targetPackagePath + package + target + lib +  game_provider_api);
            if "game-provider" != package:
                shutil.copy(targetPackagePath + package + target + lib + game_engine, basePath + package + "/" + game_engine);
                print("copy engine " + targetPackagePath + package + target + lib + game_engine);
        else:
            shutil.copytree(targetPackagePath + package + target + package + warSuffix ,  basePath + package +ROOT);
            print("copy tomcat package  " + targetPackagePath + package + target + package + warSuffix  );
    print("end copy  package ...")

    random_input = input(" 请输入任意字符结束. ");
print("end");
